<template>
    <el-select 
        v-model="formData" 
        :placeholder="props.tips"
        clearable filterable
        remote reserve-keyword
        :remote-method="loadDs"
        :loading="remoteLoading"
        @change="dataChange">
        <el-option
          v-for="dict in dsOptions"
          :key="dict.value"
          :label="dict.label"
          :value="dict.value"
        />
      </el-select>
</template>

<script setup name="Remote">
import { dsData } from "@/api/dev/dataset";

const emit = defineEmits(['update'])

const formData = ref(null);
const dsOptions = ref([]);
const remoteLoading = ref(false);

const props = defineProps({
  modelValue: [String, Number],
  // 数据集
  dsCode: {
    type: String,
    required: true,
  },
  // 展示方式
  tips: {
    type: String,
    default: '请输入关键字',
  }
});

watch(() => props.modelValue, val => {
    formData.value = val;  
},{ deep: true, immediate: true });


watch(() => props.dsCode, val => {
  if(val != null){
    loadDs(null)
  }else{
    dsOptions.value = [];
  }
},{ deep: true, immediate: true });
    
function loadDs(label) {
  let query = {
    label:label,
    value: props.modelValue
  };
  if(!props.modelValue && !label){
    dsOptions.value = [];
    return;
  }
  dsData(props.dsCode, query).then(resp => {
      dsOptions.value = resp.data;
  });
}

function dataChange() {   
    emit("update:modelValue", formData.value);
}
</script>

